package highlevel.thread;

public class AccountWithoutSync {
	private Account account = new Account();
	private Thread[] thread = new Thread[100];
	
	public static void main(String[] args) {
		AccountWithoutSync test = new AccountWithoutSync();
		System.out.println("What is Balance ? "+test.account.balance);
	}
	
	public AccountWithoutSync(){
		ThreadGroup g = new ThreadGroup("group");
		boolean done = false;
		
		//create and launch 100 threads
		for(int i=0;i<100;i++){
			thread[i]  = new Thread(g, new AddAPennyThread(), "t");
			thread[i].start();
		}
		
		//check if all the threads are finished
		while(!done)
			if(g.activeCount()==0)
				done = true;
	}
	
	class AddAPennyThread extends Thread{
		public void run(){
			account.deposit(1);
		}
	}
	
	class Account {
		private int balance = 0;
		
		public int getBalance(){
			return balance;
		}
		
		public synchronized void deposit(int amount){
			int newBalance = balance + amount;
			//this delay is deliberately added to magnify the 
			//data.corruption problem and make it easy to see.
			try {
				Thread.sleep(2);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			balance = newBalance;
		}
	}
}
